package com.example;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class HttpClient {

    public static class HttpResponse {
        public final byte[] body;
        public final String status;
        public final List<String> fields;

        HttpResponse(byte[] response) {
            // Find the separator between headers and body
            int separatorIndex = -1;
            for (int i = 0; i < response.length - 3; i++) {
                if (response[i] == '\r' && response[i + 1] == '\n' && response[i + 2] == '\r' && response[i + 3] == '\n') {
                    separatorIndex = i;
                    break;
                }
            }

            if (separatorIndex == -1) {
                throw new IllegalArgumentException("Invalid HTTP response: no CRLF CRLF found");
            }

            // Split the response into headers and body
            byte[] headersPart = Arrays.copyOfRange(response, 0, separatorIndex);
            this.body = Arrays.copyOfRange(response, separatorIndex + 4, response.length);

            // Convert headers part to string and split it into individual headers
            String headersString = new String(headersPart, StandardCharsets.UTF_8);
            String[] headers = headersString.split("\r\n");
            this.fields = new ArrayList<>();

            // The first line is the status line
            this.status = headers[0];

            // Parse the rest as headers
            this.fields.addAll(Arrays.asList(headers).subList(1, headers.length));
        }
    }

    public static HttpResponse sendRequest(String request, byte[] host, int port) {
        // 调用Socket.newSocket方法创建一个Socket对象
        var socket = Socket.newSocket(host, port);
        // 调用connect方法连接到服务器
        var socket2 = socket.connect();

        System.out.printf("Sending request:%n%s", request);


        // 调用send方法发送请求
        socket2.send(request.getBytes());

        byte[] response = socket2.recv();

        byte[] httpResponse = Packet.buildFromBytes(response).data();


//        // 创建一个列表来存储接收到的数据分片
//        List<Packet> packets = new ArrayList<>();
//
//        // 多次调用recv方法直到返回null
//        byte[] fragment;
//        while (true){
//            fragment = socket2.recv();
//            if (fragment == null) {
//                System.out.println("Received null fragment. Exiting loop.");
//                break;
//            }
//            Packet packet = new Packet(fragment);
//            packets.add(packet);
//            System.out.println("Received packet with seq number: " + packet.seqNumber());
//        }
//
//        packets.sort(Comparator.comparingLong(Packet::seqNumber));
//
//        System.out.println(packets.size());
//
//        List<byte[]> allPacketData = new ArrayList<>();
//
//        // 遍历排序后的列表，将每个包的数据提取出来并添加到allPacketData中
//        for (Packet packet : packets) {
//            allPacketData.add(packet.data());
//        }
//
//        // 计算所有数据的总长度
//        int totalLength = allPacketData.stream().mapToInt(data -> data.length).sum();
//
//        // 创建一个新的byte[]，用于存储所有的数据
//        byte[] allData = new byte[totalLength];
//
//        // 将所有包的数据拼接到allData中
//        int currentIndex = 0;
//        for (byte[] currentData : allPacketData) {
//            System.arraycopy(currentData, 0, allData, currentIndex, currentData.length);
//            currentIndex += currentData.length;
//        }
//
//
//        HttpResponse httpResponse;
//        if (null != Main.decodeText(allData)) {
//            System.out.println(Main.decodeText(allData));
//            httpResponse = new HttpResponse(allData);
//        } else {
//            System.out.println("No body");
//            socket2.close();
//            return null;
//        }
//
//        // 现在，response包含了所有接收到的数据



        System.out.println("Response Received.");


//        HttpResponse httpResponse;
//        System.out.println("Response header: ");
//        System.out.println(httpResponse.status);
//        httpResponse.fields.forEach(System.out::println);

        socket2.close();

        return new HttpResponse(httpResponse);
    }

    public static boolean isHttpResponseComplete(String response) {
        // Check if the response contains the separator between headers and body
        if (!response.contains("\r\n\r\n")) {
            return false;
        }

        // Split the response into headers and body
        String[] parts = response.split("\r\n\r\n", 2);
        String body = parts.length > 1 ? parts[1] : "";

        // Check if the headers contain a Content-Length field
        String[] headers = parts[0].split("\r\n");
        for (String header : headers) {
            if (header.startsWith("Content-Length: ")) {
                // Get the expected body length
                int expectedLength = Integer.parseInt(header.substring("Content-Length: ".length()));
                // Check if the actual body length is less than the expected length
                if (body.length() < expectedLength) {
                    return false;
                }
            }
        }

        // If there is no Content-Length field, or the actual body length is not less than the expected length,
        // then the response is complete
        return true;
    }

}
